package hhtc.jsjds.task;

import hhtc.jsjds.entity.FinalSeqPojo;
import hhtc.jsjds.redis.RedisProvider;
import hhtc.jsjds.service.AreaService;
import hhtc.jsjds.service.FinalSeqService;
import hhtc.jsjds.vo.AreaGroupVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ZhangYi zhangyi-time@foxmail.com
 * @date 2021/3/29 14:36
 */
@Slf4j
@Component
public class AsyncTask {


    @Autowired
    private AreaService areaService;

    @Autowired
    private FinalSeqService finalSeqService;

    @Autowired
    private RedisProvider redisProvider;

    @Transactional(rollbackFor = Exception.class)
    @Async("taskExecutor")
    public void shuffleGroup() {
        List<AreaGroupVO> areaGroupVOS = areaService.getGroupConcatIdAndCategoryId();
        for (AreaGroupVO areaGroupVO : areaGroupVOS) {
            String[] areaGroupIds = areaGroupVO.getGroupId().split(",");
            String[] areaCategoryIds = areaGroupVO.getGroupCategoryId().split(",");
            AtomicInteger idx = new AtomicInteger(1);
            for (String areaId : areaGroupIds) {
                insertShuffleGroupData(areaCategoryIds, idx, areaId);
            }

        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Async("taskExecutor")
    public void insertShuffleGroupData(String[] areaCategoryIds, AtomicInteger idx, String areaId) {
        for (String categoryId : areaCategoryIds) {
            List<FinalSeqPojo> list = finalSeqService.getFinalSeqGroupById(Integer.parseInt(areaId), Integer.parseInt(categoryId));
            if (CollectionUtils.isNotEmpty(list)) {
                synchronized (this) {
                    Collections.shuffle(list);
                    List<FinalSeqPojo> insertData = new ArrayList<>();
                    for (FinalSeqPojo finalSeqPojo : list) {
                        finalSeqPojo.setSequence(idx.getAndIncrement());
                        finalSeqPojo.setArea(Integer.parseInt(areaId));
                        insertData.add(finalSeqPojo);
                    }
                    finalSeqService.saveBatch(insertData);
                }
            }
        }
    }


}
